window.addEventListener('load', () => {
    const mainBox = document.querySelector('main');
    const h3 = mainBox.querySelector('h3');
    const qiu = mainBox.querySelector('div');
    const ctrl = document.getElementById('ctrl');
    const viewPortWidth = mainBox.clientWidth;
    const viewPortHeight = mainBox.clientHeight;
    let x = 0;    //横坐标
    let y = 0; //纵坐标
    let tempX = 6;
    let tempY = 6;
    let ctrlMove = 0;
    let speed = 20;
    let intervleCt;
    let fenShu = 0, beiShu = 1;
    function run() {
        intervleCt = setInterval(() => {
            x += tempX;
            y += tempY;
            qiu.style.left = x + 'px';
            qiu.style.top = y + 'px';
            //碰到上边界
            if (y < 0 || y > viewPortHeight - 60) {
                tempY = -tempY;
            }
            //碰到左右边界
            if (x < 0 || x > viewPortWidth - 40) {
                tempX = -tempX;
            }
            if(y > viewPortHeight - 60) {
                if (x > ctrlMove + 200 || x < ctrlMove - 40) {
                    clearInterval(intervleCt);
                    alert('游戏结束');
                    tempX = 6;
                    tempY = 6;
                    speed = 20;
                    x = 0;
                    y = 0;
                    beiShu = 1;
                    fenShu = 0;
                    h3.innerHTML = `0分`;
                    run();
                }else {
                    if (--speed == 1) {
                        speed = 2;
                        if (tempX > 0) {
                            tempX++;
                        }else {
                            tempX--;
                        }
                        if (tempY > 0) {
                            tempY++;
                        }else {
                            tempY--;
                        }
                    }
                    h3.innerHTML = `${fenShu += 10 * beiShu++}分`;
                    clearInterval(intervleCt);
                    run();
                }
            }
        }, speed);
    }
    run();
    mainBox.addEventListener('mousemove', e => {
        if (e.target.localName == 'main') {
            if (e.layerX < 100) {
                ctrl.style.left = '0px';
            }else if (e.layerX > viewPortWidth - 100) {
                ctrl.style.left = viewPortWidth - 200 + 'px';
            }else {
                ctrl.style.left = e.layerX - 100 + 'px';
            }
            ctrlMove = ctrl.offsetLeft;
        }
    });
});